import React, { useState, useMemo, useEffect } from 'react';

import { observer } from 'mobx-react-lite';
import { Button, Table, DataSet } from 'choerodon-ui/pro';
import { ColumnProps } from 'choerodon-ui/pro/lib/table/Column';
import { TableEditMode } from 'choerodon-ui/pro/lib/table/enum';
import notification from 'utils/notification';
import { ColumnLock } from 'choerodon-ui/pro/lib/table/enum';
import { TableQueryBarType } from 'choerodon-ui/pro/lib/table/enum';
import { getResponse } from 'utils/utils';
import { TableListDataSetConfig, saveAll } from './store';


const OrderLine = props => {
  const {
    orderId, // 请求单id，即头id
    moneyChangeFlow,
    lineDetailEditFlow,
    formDataSet,
    flowFormQuery,
    orderBoCode,
    orderLineBoCode,
    handleRunEvent,
    setEventFunction,
    handleChangeOutputParams,
    ...extralProps
  } = props;
  const headerBoCode = orderBoCode || 'SRQ_ORDER';
  const lineBoCode = orderLineBoCode || 'SRQ_ORDER_LINES';

  const dataSet = useMemo(() => new DataSet(TableListDataSetConfig(lineBoCode)), []);

  React.useEffect(() => {
    Object.entries(extralProps || {}).forEach(([key, value]) => {
      handleChangeOutputParams({ property: key, data: value });
    });
  }, [...Object.values(extralProps)]);

  useEffect(() => {
    const load = ({ dataSet }) => {
      const totalMoney = (dataSet.toData() as any[]).reduce((t, c) => {
        if (!Number.isNaN(+c.lineAmount)) {
          t += c.lineAmount;
        }
        return t;
      }, 0);
      handleChangeOutputParams({
        property: 'totalMoney',
        data: totalMoney,
      });
      if ((moneyChangeFlow as any)?.flowCode) {
        handleRunEvent(moneyChangeFlow.flowCode);
      }
    };

    const update = ({ name, value, record }) => {
      if (name === 'lineAmount') {
        const totalMoney = (record.dataSet.toData() as any[]).reduce((t, c) => {
          if (!Number.isNaN(+c.lineAmount)) {
            t += c.lineAmount;
          }
          return t;
        }, 0);
        handleChangeOutputParams({
          property: 'totalMoney',
          data: totalMoney,
        });
        if ((moneyChangeFlow as any)?.flowCode) {
          handleRunEvent(moneyChangeFlow.flowCode);
        }
      }
    };

    dataSet.addEventListener('load', load);
    dataSet.addEventListener('update', update);

    return () => {
      dataSet.removeEventListener('load', load);
      dataSet.removeEventListener('update', update);
    };
  }, [dataSet]);

  useEffect(() => {
    const query = async () => {
      if(!orderId) {
        return;
      }
      dataSet.setQueryParameter('orderId', orderId);
      await dataSet.query();
    };
    query();
    setEventFunction?.('query', (lineNum, lineAmount, lineType) => {
      dataSet.setQueryParameter('orderId', orderId);
      dataSet.setQueryParameter('lineNum', lineNum);
      dataSet.setQueryParameter('lineAmount', lineAmount);
      dataSet.setQueryParameter('lineType', lineType);
      dataSet.query().then(() => {
        dataSet.setQueryParameter('lineNum', undefined);
        dataSet.setQueryParameter('lineAmount', undefined);
        dataSet.setQueryParameter('lineType', undefined);
      });
    });
  }, [orderId]);

  const [editor] = useState(true);

  const handleAdd = () => {
    dataSet.create({ orderId });
  };

  const handleAddDetail = () => {
    if ((lineDetailEditFlow as any)?.flowCode) {
      handleRunEvent(lineDetailEditFlow.flowCode);
    } else {
      notification.info({
        description: '请配置入参事件流lineDetailEditFlow，用于新增行及明细',
      });
    }
  };

  const saveLine = () => {
    dataSet.submit();
  };

  const saveHeaderAndLine = async () => {
    if (!formDataSet) return;
    const formFlag = await formDataSet.validate();
    if (!formFlag) return;
    const tableFlag = await dataSet.validate();
    if (!tableFlag) return;
    const formData = formDataSet.toData();
    const tableData = dataSet.toData();
    const bodyData = {
      ...(formData?.[0] || {}),
      [lineBoCode]: tableData,
    };

    const businessObjectRelation = {
      businessObjectCode: headerBoCode,
      componentRelationHeads: [
        {
          businessObjectCode: lineBoCode,
          displayCode: lineBoCode,
          componentRelationLines: [{ field: 'orderId', parentField: 'id' }],
        },
      ],
    };

    const res = await saveAll({
      header: {
        'business-object-relation': JSON.stringify(businessObjectRelation),
      },
      body: [bodyData],
      headerBoCode,
    });
    if (getResponse(res)) {
      notification.success({
        message: '保存成功',
      });
      const isCreate = !orderId;
      if (!isCreate) {
        if ((flowFormQuery as any)?.flowCode) {
          await handleRunEvent(flowFormQuery.flowCode);
        }
      } else {
        dataSet.setQueryParameter('orderId', res[0].id);
      }
      await dataSet.query();
    }
  };

  useEffect(() => {
    setEventFunction?.('saveHeaderAndLine', saveHeaderAndLine);
    setEventFunction?.('saveLine', saveLine);
    setEventFunction?.('add', handleAdd);
    setEventFunction?.('delete', () => {
      if (!dataSet.selected.length) {
        notification.warning({
          description: '请选择需要删除的数据',
        });
        return;
      }
      dataSet.delete(dataSet.selected);
    });
  }, [orderId]);

  const buttons = [
    <Button icon="playlist_add" onClick={handleAdd} key="add">
      新增
    </Button>,
    <Button icon="save" onClick={saveLine} key="save" disabled={!orderId}>
      保存
    </Button>,
    <Button
      key="delete"
      icon="delete_black-o"
      onClick={() => {
        dataSet.delete(dataSet.selected, true);
      }}
      disabled={dataSet.selected.length === 0}
    >
      删除
    </Button>,
    <Button icon="playlist_add" onClick={handleAddDetail} key="add">
     新增行及明细
    </Button>,
  ].filter(Boolean);

  const commands = (): any => [
    'edit',
    ['delete', { color: 'red' }],
  ];

  const columns: ColumnProps[] = [
    { name: 'lineNum', editor },
    { name: 'lineType', editor },
    { name: 'itemId_lovObj', editor },
    { name: 'lineQuantity', editor },
    { name: 'unitPrice', editor },
    { name: 'lineAmount' },
    {
      header: '操作',
      width: 150,
      command: commands,
      lock: ColumnLock.right,
    }
  ];

  return (
    <Table
      editMode={TableEditMode.inline}
      buttons={buttons}
      dataSet={dataSet}
      columns={columns}
      queryBar={TableQueryBarType.filterBar}
    />
  );
};

export default observer(OrderLine);
